<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请您输入SPU名称"
        v-model="spuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select
        placeholder="请您选择品牌"
        style="width: 200px"
        v-model="spuParams.tmId"
      >
        <el-option
          v-for="item in allTrademark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        placeholder="请您输入描述"
        type="textarea"
        v-model="spuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU照片">
      <el-upload
        v-model:file-list="spuImageList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        style="width: 200px"
        v-model="saleAttrIdAndName"
        :placeholder="
          unselectedAttr.length
            ? `还有${unselectedAttr.length}项属性未选择`
            : '无'
        "
      >
        <el-option
          v-for="item in unselectedAttr"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        type="primary"
        icon="Plus"
        style="margin-left: 20px"
        @click="addAttr"
        :disabled="saleAttrIdAndName ? false : true"
        >添加属性</el-button
      >
      <el-table border style="margin: 20px 0px" :data="spuSaleAttr">
        <el-table-column
          label="序号"
          width="100px"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          label="属性名"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #default="{ row, $index }">
            <el-tag
              v-for="(item, index) in spuSaleAttr[$index].spuSaleAttrValueList"
              :key="item.id"
              closable
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              style="margin: 0px 5px"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-button
              v-if="!row.flag"
              type="primary"
              size="small"
              icon="Plus"
              @click="toEdit(row)"
              style="margin: 0px 5px"
            ></el-button>
            <el-input
              v-else
              v-model="row.newSaleAttrValueName"
              placeholder="请你输入属性值的名称"
              size="small"
              @blur="toLook(row)"
              style="width: 200px"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #default="{ row, $index }">
            <el-button
              type="danger"
              icon="delete"
              size="small"
              @click="spuSaleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="save"
        :disabled="spuSaleAttr.length ? false : true"
        >保存</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import {
    reqAllTrademark,
    reqSpuImageList,
    reqSpuSaleAttr,
    reqAllBaseSaleAttr,
    reqAddOrUpdateSpuInfo,
  } from '@/api/product/spu'
  import type {
    SpuData,
    Trademark,
    spuImageData,
    spuSaleAttrData,
    baseSaleAttrData,
  } from '@/api/product/spu/type'
  import { ElMessage } from 'element-plus'
  let $emit = defineEmits(['changeScene'])

  let allTrademark = ref<Trademark[]>([])
  let spuImageList = ref<spuImageData[]>([])
  let spuSaleAttr = ref<spuSaleAttrData[]>([])
  let allBaseSaleAttr = ref<baseSaleAttrData[]>([])
  let spuParams = ref<SpuData>({
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
  })
  let dialogVisible = ref<boolean>(false) //控制图片预览是否显示
  let dialogImageUrl = ref<string>('')
  let unselectedAttr = ref<baseSaleAttrData[]>([]) //储存未被选择的销售属性，用于select组件遍历
  let saleAttrIdAndName = ref<string>('') //收集选择的属性id与属性名

  const cancel = () => {
    $emit('changeScene', { flag: 0, toWhichPage: 'toCurrent' })
  }

  const initHasSpuData = async (row: SpuData) => {
    spuParams.value = row

    let result = await reqAllTrademark()
    allTrademark.value = result.data
    // 确保 row.id 存在
    if (Number(row.id) != null) {
      let result1 = await reqSpuImageList(Number(row.id))
      spuImageList.value = result1.data.map((item) => {
        return {
          name: item.imgName,
          url: item.imgUrl,
        }
      })

      let result2 = await reqSpuSaleAttr(Number(row.id))
      spuSaleAttr.value = result2.data
    } else {
      console.error('SPU ID 不存在，无法请求关联数据')
    }
    let result3 = await reqAllBaseSaleAttr()
    allBaseSaleAttr.value = result3.data
  }

  const initSpuData = async (c3Id: string) => {
    let result = await reqAllTrademark()
    allTrademark.value = result.data
    let result1 = await reqAllBaseSaleAttr()
    allBaseSaleAttr.value = result1.data
    //清空已有数据
    spuParams.value = {
      category3Id: c3Id,
      spuName: '',
      description: '',
      tmId: '',
      spuImageList: [],
      spuSaleAttrList: [],
    }
    spuImageList.value = []
    spuSaleAttr.value = []
    saleAttrIdAndName.value = ''
    //清除已有的spuId,防止上次编辑spu后仍然残留
    spuParams.value.id = 0 //
  }

  defineExpose({ initHasSpuData, initSpuData })

  const handlePictureCardPreview = (uploadFile: any) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
  }

  unselectedAttr = computed(() => {
    let unselectedAttrArr: baseSaleAttrData[] = allBaseSaleAttr.value.filter(
      (item) => {
        return spuSaleAttr.value.every((i) => {
          return i.baseSaleAttrId != item.id
        })
      },
    )
    return unselectedAttrArr
  })

  const addAttr = () => {
    let [baseSaleAttrId, saleAttrName] = saleAttrIdAndName.value.split(':')
    let attrObj = {
      baseSaleAttrId: Number(baseSaleAttrId),
      saleAttrName,
      spuSaleAttrValueList: [],
    }
    spuSaleAttr.value.push(attrObj)
    saleAttrIdAndName.value = ''
  }

  const toEdit = (row: spuSaleAttrData) => {
    row.flag = true
  }

  const toLook = (row: spuSaleAttrData) => {
    const { baseSaleAttrId, newSaleAttrValueName } = row
    let newSaleAttrValueObj = {
      baseSaleAttrId: baseSaleAttrId,
      saleAttrValueName: newSaleAttrValueName as string,
    }

    //非法情况1
    if (!newSaleAttrValueName || newSaleAttrValueName.trim() === '') {
      ElMessage({
        type: 'error',
        message: '属性值不能为空',
      })
      return false
    }
    let isRepeat = row.spuSaleAttrValueList.find((item) => {
      return item.saleAttrValueName == newSaleAttrValueName
    })
    if (isRepeat) {
      ElMessage({
        type: 'error',
        message: '属性值不能重复',
      })
      return false
    }
    row.spuSaleAttrValueList.push(newSaleAttrValueObj)
    row.flag = false
    row.newSaleAttrValueName = '' //需要清空原有的数据，否则下一次新增属性值时会出现
  }

  const save = async () => {
    //整理参数spuParams
    //商品图片列表需要重新映射
    spuParams.value.spuImageList = spuImageList.value.map((item: any) => {
      return {
        imgName: item.name,
        imgUrl: (item.response && item.response.data) || item.url,
      }
    })
    //商品属性值列表需要用收集的数据赋值
    spuParams.value.spuSaleAttrList = spuSaleAttr.value
    //发请求
    let result = await reqAddOrUpdateSpuInfo(spuParams.value)
    //成功|失败提示
    if (result.code === 200) {
      ElMessage({
        type: 'success',
        message: spuParams.value.id ? '修改属性成功' : '添加属性成功',
      })
      if (spuParams.value.id) {
        $emit('changeScene', { flag: 0, toWhichPage: 'toCurrent' })
      } else {
        $emit('changeScene', { flag: 0, toWhichPage: 'toFirst' })
      }
    } else {
      ElMessage({
        type: 'error',
        message: spuParams.value.id ? '修改属性失败' : '添加属性失败',
      })
    }
  }
</script>

<style scoped></style>
